// 该文件中的内容是通过 app.js 导入后在后端运行的

const express = require('express');
const mysql = require('mysql2');

// 创建数据库连接池
const pool = mysql.createPool({
  host: 'localhost',
  user: 'root',
  database: 'ecut',
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0
});


const router = express.Router();


// GET `/user/list`
router.get('/user/list',(req,resp)=>{

    // pool.query( sql , values , callback , fields );
    // 在回调函数中处理SQL语句的执行结果
    pool.query( 'SELECT id, account, email, tel FROM t_users' , (error,results) => {
        if( error ){
            resp.json( { success: false , message: '查询失败' , cause: error.name });
            return ;
        }
        resp.json( { success: true , message: '查询成功' , users: results } );
    });

});

const validate = (req,resp,next) => {
    console.log('数据校验');
    let { account , email , tel , password , confirm } = req.body ;
    // 如果 account , email , tel 都为空则向客户端返回 必须填写 其中之一

    // 如果两次输入密码不一致，则向客户端返回提示信息
    if( password != confirm ) {
        resp.json( { success: false , message: '两次密码不一致' } );
        return; // 采用 return 让当前函数立即结束
    }
    // 继续调用下一个中间件( 即调用 handleAdd 函数 )
    next();
}

const handleAdd = (req,resp) => {
    console.log('数据保存');

    let { account , email , tel , password } = req.body ;

    let promise = pool.promise();

    let sql = 'INSERT INTO t_users ( account , email , tel , password ) VALUES ( ? , ? , ? , ? )';
    let values = [ account , email , tel , password ];
    promise.query( sql , values )
           .then( array => {
               let r = array[0];
               if( r.insertId > 0 ) {
                 resp.json( { success: true , message: '保存成功' } );
               }
           }).catch( reason => {
                resp.json( { success: false , message: '保存失败' , reason: reason } );
           });
}

// POST `/user/add`
router.post('/user/add' , validate , handleAdd );

// GET `/user/remove/:id`
router.get('/user/remove/:id',(req,resp)=>{
    let { id } = req.params ;
    let sql = 'DELETE FROM t_users WHERE id = ? ';
    let p = pool.promise();
    p.query( sql , [ id ] )
     .then( ([result,fileds]) => { 
         console.log( result );
         resp.json( { success: true , message: '删除成功' });
     }).catch( reason => {
         resp.json( { success: false , message: '删除失败' });
     })
});

// GET `/user/find/:id`
router.get('/user/find/:id',(req,resp)=>{
    let { id } = req.params ;
    let sql = 'SELECT id, account, email, tel FROM t_users WHERE id = ? ';
    let p = pool.promise();
    p.query( sql , [ id ] )
     .then( ([rows,fileds]) => { 
         if( rows.length > 0 ) {
            resp.json( { success: true , message: '查询成功' , user: rows[0] });
         }
     }).catch( reason => {
         resp.json( { success: false , message: '查询失败' , reason });
     })
});

// POST `/user/modify`
router.post('/user/modify', validate , (req,resp)=>{
    let { id , account , tel , email , password } = req.body ;
    let sql = 'UPDATE t_users SET account = ? , tel = ? , email = ? , password = ? WHERE id = ?';
    let values = [ account , tel , email , password , id ];
    let p = pool.promise();
    p.query( sql , values )
     .then( ([result,fields]) => {
         console.log( result );
         resp.json( { success: true , message: '修改成功' } );
     }).catch( reason => {
        resp.json( { success: false , message: reason } );
     });
});

module.exports = router;